<template>
  <div class="title">个人中心</div>
  <div v-if="flag" class="msg">
    <div class="avatar">
      <img :src="info.avatar" alt="avatar" />
      <!-- <img v-if="avatarBase64" :src="avatarBase64" alt="Avatar" /> -->
    </div>
    <div class="name">{{ info.nickname || `用户${getUserId()}` }}</div>
    <div class="id">用户名：{{ info.username }}</div>
  </div>
  <div v-else class="msg">
    <div class="avatar">
      <img src="@/assets/avatar.png" alt="avatar" />
    </div>
    <div @click="() => { router.push({ path: '/login' }) }" class="name">请登录 / 注册</div>
  </div>
  <div v-show="flag" class="function">
    <div @click="selectUpdateMsg" class="item">
      修改个人信息
    </div>
  </div>
  <div v-show="flag" class="function">
    <div @click="change" class="item">
      退出账号
    </div>
  </div>

  <!-- <div v-show="flag" class="function">
    <div @click="editNickname" class="item">
      修改昵称
    </div>
  </div>
  <div v-show="flag" class="function">
    <div @click="editAvatar" class="item">
      修改头像
    </div>
  </div> -->

  <van-popup v-model:show="isShow" closeable position="bottom" :style="{ height: '60%' }">
    <div class="display">
      <div class="image" v-for="item in avatorArr" @click="changeAvatar(item)">
        <img :src="item" alt="">
      </div>
    </div>
  </van-popup>

  <van-dialog v-model:show="showNickname" title="修改昵称" show-cancel-button @confirm="changeNickname(nickname)">
    <van-field class="inputNickname" v-model="nickname" placeholder="请输入昵称" />
  </van-dialog>

  <layoutPopup :show="showBottom" @update:show="val => showBottom = val" @left-click="editNickname"
    @right-click="editAvatar">
    <template #left-icon>
      <i class="iconfont icon-xiugainicheng"></i>
    </template>
    <template #left-text>
      <span>修改昵称</span>
    </template>
    <template #right-icon>
      <i class="iconfont icon-touxiang"></i>
    </template>
    <template #right-text>
      <span>修改头像</span>
    </template>
  </layoutPopup>


  <!-- <van-popup v-model:show="isShow" closeable close-icon="close" position="bottom" :style="{ height: '40%' }">
    <van-uploader v-model="avatarFile" multiple :max-count="1" :after-read="afterRead" :preview-size="[200, 200]"
      upload-text="头像上传" />
  </van-popup> -->
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import router from '@/router/index.js';
import { checkPermission } from '@/utils/isLogin.js';
import { showConfirmDialog, showSuccessToast, showFailToast } from 'vant';
import { getUserId } from '@/utils/getUserId.js';
import { updateAvatar, updateNickname } from '@/api/index.js';
import layoutPopup from '@/components/layoutPopup.vue';
// import { uploadAvatarImg } from '@/api/index.js';
// import { uploadImgToBase64 } from '@/utils/handleImg.js'

onBeforeMount(async () => {
  if (!await checkPermission()) {
    return
  }
})

const token = localStorage.getItem('token')
const userInfo = localStorage.getItem('userInfo')

const flag = ref(token)
const info = ref(JSON.parse(userInfo))
const isShow = ref(false)
const isDisplay = ref(false)
const showNickname = ref(false)
const nickname = ref('')
const showBottom = ref(false)


let avatorArr = [
  'https://img1.baidu.com/it/u=3217838212,795208401&fm=253&fmt=auto&app=138&f=JPEG?w=514&h=500',
  'https://q9.itc.cn/q_70/images03/20240918/def2b7d32f2144099caf42b98753871e.jpeg',
  'https://q3.itc.cn/q_70/images03/20250202/a040a6744049458ab174a66457e256e5.jpeg',
  'https://q7.itc.cn/q_70/images03/20241013/d67d55313b8a46bcae63cf22cc52b2fc.jpeg',
  'https://q5.itc.cn/q_70/images03/20241116/2c262260fd534b35b0052aef28973685.png',
  'https://img1.baidu.com/it/u=1052397826,1513523633&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=3600954679,641662266&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=3196617431,1263013381&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img2.baidu.com/it/u=199363802,1916398725&fm=253&fmt=auto&app=120&f=JPEG?w=503&h=500',
  'https://img1.baidu.com/it/u=252741406,3488549597&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=647176915,2161300483&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=3029837478,1144772205&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=378626424,1386413315&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=434104847,2374269041&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=2103865173,489713918&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=4172393334,2310871155&fm=253&fmt=auto?w=690&h=679',
  'https://img0.baidu.com/it/u=1649316660,1778684744&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=2705597246,2913057507&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800',
  'https://img1.baidu.com/it/u=516839860,2898225680&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=748217267,3633181426&fm=253&fmt=auto&app=120&f=JPEG?w=511&h=500',
  'https://img2.baidu.com/it/u=306649616,2230355986&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=3685137112,4227852722&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=3047293562,4139874157&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=501',
  'https://img0.baidu.com/it/u=1266305302,467693145&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=212230986,3555547834&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=2743394743,692629981&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800',
  'https://img0.baidu.com/it/u=1337201637,626583960&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img2.baidu.com/it/u=3991893739,3800942515&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=434104847,2374269041&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=2103865173,489713918&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=247754306,2011451408&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=1010952571,1166529770&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=2277511832,700398111&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=2857069256,1212477516&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=3272459002,2851349848&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=502623422,912941866&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200',
  'https://img1.baidu.com/it/u=4118625424,727122652&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img0.baidu.com/it/u=887837689,3539815804&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=1028751741,3999351341&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
  'https://img2.baidu.com/it/u=3322458640,2191322390&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=2633863535,223039645&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img2.baidu.com/it/u=2429262046,4163636545&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=555',
  'https://img0.baidu.com/it/u=3639336606,2338613037&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400',
  'https://img0.baidu.com/it/u=2059977777,1877408961&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
  'https://img1.baidu.com/it/u=3685137112,4227852722&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
]

const selectUpdateMsg = () => {
  showBottom.value = true
}

const change = () => {
  showConfirmDialog({
    message:
      '确认退出吗',
  })
    .then(() => {
      // 清空本地里面的数据
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      // 跳转到登录页
      router.push('/login')
    })
    .catch(() => {
      // on cancel
    });
}

// const popUpdateMessage = () => {
//   isDisplay.value = true
// }

const updateUserInfo = async (field, value, apiCall, successMsg) => {
  try {
    const userId = getUserId()
    const res = await apiCall(userId, value)

    if (res && res.code === 200) {
      // 更新页面数据
      info.value[field] = value

      // 更新 localStorage
      const updatedUserInfo = JSON.parse(localStorage.getItem('userInfo'))
      if (updatedUserInfo) {
        updatedUserInfo[field] = value
        localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
      }

      showSuccessToast(`${successMsg}成功`)
      return true
    }
    return false
  } catch (error) {
    showFailToast(successMsg + '失败')
    console.error(`${successMsg}出错:`, error)
    return false
  }
}

const editNickname = () => {
  showBottom.value = false
  showNickname.value = true
}

const changeNickname = async (nickname) => {
  if (!nickname) {
    showFailToast('昵称不能为空')
    return
  }
  const success = await updateUserInfo('nickname', nickname, updateNickname, '昵称修改')
  if (success) {
    showNickname.value = false
  }
}
const editAvatar = () => {
  showBottom.value = false
  isShow.value = true
}

// 修改头像的方法
const changeAvatar = async (image) => {
  const success = await updateUserInfo('avatar', image, updateAvatar, '头像修改')
  if (success) {
    isShow.value = false
  }
}

// const avatarFile = ref([]);
// const avatarBase64 = ref('')
// const afterRead = async (file) => {
//   // 此时可以自行将文件上传至服务器
//   // const res = await uploadImgToBase64(file)
//   console.log(file);
//   showConfirmDialog({
//     message:
//       '确认改为该头像吗',
//   })
//     .then(async () => {
//       if (file && file.file) {
//         const reader = new FileReader();
//         reader.onload = (e) => {
//           avatarBase64.value = e.target.result; // 将结果赋值给数据属性

//           console.log('shfohao', avatarBase64.value, 'base64编码后的样子');
//         };

//         reader.onerror = (error) => {
//           console.error('FileReader error', error);
//         };
//         reader.readAsDataURL(file.file); // 读取文件内容
//       }
//       const res = await uploadAvatarImg({ id: info.id, image: avatarBase64.value })
//       console.log(res);
//       isShow.value = false;
//     })
//     .catch(() => {
//       // on cancel
//     });
// };
</script>

<style lang="less" scoped>
.title {
  height: 50px;
  font-weight: 500;
  font-size: 18px;
  color: #000000;
  line-height: 50px;
  text-align: center;
}

.msg {
  height: 200px;
  width: 100%;
  background: url("@/assets/personbg.png") no-repeat center center;
  background-size: cover;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;

  .avatar {
    margin-top: 30px;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .name {
    font-weight: 500;
    font-size: 20px;
    color: black;
  }

}

.function {
  margin: 0 16px;
  margin-top: 20px;

  .item {
    margin-bottom: 5px;
    height: 54px;
    line-height: 54px;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
    padding-left: 50px;
    box-sizing: border-box;
    border: 1px solid #F3F4F6;
  }
}

.inputButton {
  width: 80%;
  height: 50px;
}

.text {
  text-align: center;
  font-size: 18px;
}

.display {
  width: 100%;

  .image {
    width: 1.9rem;
    height: 1.9rem;
    float: left;
    margin-left: 2px;
    margin-top: 2px;

    img {
      width: 100%;
    }
  }
}

.inputNickname {
  width: 80%;
  margin: auto;
}
</style>